package com.atguigu.guli.service.oss.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.oss.config.OssProperties;
import com.atguigu.guli.service.oss.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@Slf4j
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    OssProperties ossProperties;
    @Override
    public String upload(MultipartFile file, String module) {
        try {
            String originalFilename = file.getOriginalFilename();
            // avatar/年-月-日/唯一的文件名 文件后缀     日期路径
            String objectName = module+ new DateTime().toString("/yyyy/MM/dd/")
                    + UUID.randomUUID().toString().replace("-" , "")
                    + originalFilename.substring(originalFilename.lastIndexOf("."));
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(ossProperties.getScheme()+ossProperties.getEndpoint(),
                    ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());

            InputStream inputStream = file.getInputStream();
            // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
            ossClient.putObject(ossProperties.getBucketName(), objectName, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();
            String path = ossProperties.getScheme()+ossProperties.getBucketName()+"."+ossProperties.getEndpoint()+"/"+objectName;
            // System.out.println("上传文件的访问地址为："+ path);
            log.info("上传图片后的地址：{}" , path);
            return path;
        } catch (Exception e) {
//            e.printStackTrace();
            log.error(ExceptionUtils.getStackTrace(e));
            //我们可以自定义异常：决定如何给前端响应异常描述信息
            throw new GuliException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
    }

    @Override
    public void delete(String path, String module) {
        try {
            OSS ossClient = new OSSClientBuilder().build(ossProperties.getScheme()+ossProperties.getEndpoint(),
                    ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
//        String path = "https://sh210108-guli.oss-cn-shanghai.aliyuncs.com/avatar/2021/05/22/908decd63dad4eefa10243e006a1d2e2.jpg";
            // 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
            String delObjectName = path.substring(path.lastIndexOf(module));
//        System.out.println("delObjectName = " + delObjectName);
            //objectName:是桶内要删除文件的相对路径+文件名
            ossClient.deleteObject(ossProperties.getBucketName(), delObjectName);
            // 关闭OSSClient。
            ossClient.shutdown();
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
            throw new GuliException(ResultCodeEnum.FILE_DELETE_ERROR);
        }
    }
}
